import RemoteSelect from '@/components/RemoteSelect';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Divider, message, Modal, Tag } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
// import ZoneEditForm from '../Zones/components/EditForm';
import { getZoneSelectionList } from '../Zones/service';
import ParkTurnoverDetail from './components/ParkingOrderDetailView';
import type { ParkingOrderTableListItem } from './data';
import { parkExit, queryParkingList } from './service';
import { ParkingState, ParkingType } from './utils/utils';
// import AdvancePayment from '@/pages/ParkingOrder/components/AdcancePayment';
// import styles from './style.less';

interface ParkTurnOverProp {
  orderNo?: string;
  zoneIdlist: zoneId;
}
interface zoneId {
  id: number;
  name: string;
}

const ParkingOrderTableList: React.FC<ParkTurnOverProp> = (props) => {
  const { orderNo, zoneIdlist } = props;
  const [sorter, setSorter] = useState<string>('');
  const actionRef = useRef<ActionType>();
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [clickItemId, setClickItemId] = useState<number>();
  // const [phoneShow, setPhoneShow] = useState<boolean>(false);
  // const [advanceAmount, setAdvanceAmount] = useState<ParkingOrderTableListItem | undefined>(
  //   undefined,
  // );

  const handleExit = async (fields: { id: number }) => {
    const hide = message.loading('正在结束停车');
    try {
      await parkExit(fields);
      hide();
      message.success('结束停车成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('结束停车失败请重试！');
      return false;
    }
  };

  // @ts-ignore
  const columns: ProColumns<ParkingOrderTableListItem>[] = [
    {
      title: '订单编号',
      dataIndex: 'order_no',
      width: '7vw',
      hideInSearch: false,
      ellipsis: true,
      render: (_, record) => <div>{record.id || '_'}</div>,
    },
    {
      title: '车场名称',
      dataIndex: 'zone',
      width: '7vw',
      hideInSearch: false,
      render: (_, record) => <div>{record.zone_name || '未知'}</div>,
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      renderFormItem: (_, {}) => (
        <RemoteSelect
          getPopupContainer={(triggerNode) => triggerNode.parentElement} // 保证选择菜单不会随着页面滚动
          fieldNames={{ key: 'id', value: 'id', label: 'name' }}
          request={(search) => getZoneSelectionList({ name: search })}
        />
      ),
    },
    {
      title: '车位号',
      dataIndex: 'space_name',
      hideInSearch: true,
      width: '5vw',
      render: (_, record) => <div>{record.space_name || '未知'}</div>,
    },
    {
      title: '车牌号',
      dataIndex: 'plate_number',
      hideInSearch: true,
      width: '6vw',
      order: 20,
      render: (_, record) => <div>{record.plate_number || '未知'}</div>,
    },
    {
      title: '手机号',
      width: '6vw',
      dataIndex: 'phone',
      order: 10,
      hideInSearch: true,
      render: (_, record) => <div>{record.phone || '未知'}</div>,
    },
    {
      title: '驶入时间',
      dataIndex: 'begin_time',
      order: 18,
      hideInSearch: true,
      ellipsis: true,
      width: '8vw',
      render: (_, record) => {
        if (record.begin_time) {
          return <Tag>{record.begin_time}</Tag>;
        }
        return <Tag> </Tag>;
      },
      // renderFormItem: (_, { onChange }) => {
      //   return (
      //     <DatePicker.RangePicker
      //       showTime
      //       format="YYYY-MM-DD HH:mm"
      //       onChange={(value) => onChange && onChange(value)}
      //     />
      //   );
      // },
    },
    {
      title: '驶出时间',
      dataIndex: 'end_time',
      hideInSearch: true,
      ellipsis: true,
      width: '8vw',
      render: (_, record) => {
        if (record.end_time && record.begin_time) {
          return <Tag>{record.end_time}</Tag>;
        } else if (record.begin_time && !record.end_time) {
          return <Tag> </Tag>;
        }
        return <Tag> </Tag>;
      },
    },
    {
      title: '停车类型',
      dataIndex: 'type',
      order: 15,
      hideInSearch: true,
      width: '5vw',
      valueEnum: ParkingType.valueEnumMap(),
    },
    {
      title: '状态',
      dataIndex: 'order_status',
      order: 16,
      width: '5vw',
      hideInSearch: true,
      valueEnum: ParkingState.valueEnumMap(),
    },
    {
      title: '应收金额(元)',
      dataIndex: 'total_amount',
      hideInSearch: true,
      width: '4vw',
      render: (_, record) => `￥${record?.total_amount || 0}元`,
    },
    {
      title: '实收金额(元)',
      dataIndex: 'total_actual_amount',
      hideInSearch: true,
      width: '4vw',
      render: (_, record) => `￥${record?.total_actual_amount || 0}元`,
    },
    {
      title: '操作',
      dataIndex: 'options',
      hideInSearch: true,
      width: '6vw',
      render: (_, record) => {
        const onClickDetail = () => {
          setDetailVisible(true);
          setClickItemId(record.id);
        };
        // const onClickOrderCancel = () => {
        //   setAdvanceAmount(record);
        // };
        const onClickExitpark = () => {
          const { id } = record;
          Modal.confirm({
            title: `结束停车`,
            content: (
              <>
                <Divider />
                <p>是否要手动结束当前车辆的停车状态？</p>
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleExit({ id });
            },
            centered: true,
            width: '35vw',
            style: { height: '15vw' },
          });
        };
        if (
          record.order_status == 5 ||
          record.order_status == 6 ||
          (record.order_status == 1 && record.end_time == null)
        ) {
          return (
            <div>
              <a onClick={onClickDetail}>详情</a>
              <Divider type="vertical" />
              <a onClick={onClickExitpark}>结束停车</a>
            </div>
          );
        } else {
          return <a onClick={onClickDetail}>详情</a>;
        }
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<ParkingOrderTableListItem>
        headerTitle="停车记录"
        actionRef={actionRef}
        rowKey="id"
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<ParkingOrderTableListItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        tableAlertRender={() => false}
        request={async (params = {}) => {
          const orderNumber = orderNo;
          const zoneNumber = zoneIdlist;
          const { current: page, pageSize, ...filter } = params;
          const res = queryParkingList({
            page,
            pageSize,
            order_no: orderNumber,
            zone: zoneNumber,
            ...filter,
          });
          return res;
        }}
        columns={columns}
        rowSelection={false}
      />
      {!!clickItemId && detailVisible && (
        <ParkTurnoverDetail
          visible={!!clickItemId && detailVisible}
          onClose={() => setDetailVisible(false)}
          id={clickItemId}
        />
      )}
      {/* <AdvancePayment
        record={advanceAmount}
        onSubmit={() => setAdvanceAmount(undefined)}
        modalVisible={advanceAmount !== undefined}
        visibleHandler={() => {
          setAdvanceAmount(undefined);
        }}
        onCancel={() => {
          setAdvanceAmount(undefined);
        }}
      /> */}
    </PageHeaderWrapper>
  );
};

export default ParkingOrderTableList;
